﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BotonJXC.Forms.Events;
using BotonJXC.Entity;
using BotonJXC.BLL;
using NHibernate;
using BotonJXC.DAO;
using ComponentFactory.Krypton.Toolkit;

namespace BotonJXC.Forms
{
    public partial class ProductForm : BaseMdiForm
    {
        ActionTypes _doubleListRowAction = ActionTypes.None;
        ProductBLL _productBll = new ProductBLL();
        ProductTypeBLL _productTypeBll = new ProductTypeBLL();
        UnitBLL _unitBll = new UnitBLL();
        WarehouseBLL _warehouseBll = new WarehouseBLL();
        LogisticsModelBLL _logisticsModelBll = new LogisticsModelBLL();
        SupplierBLL _supplierBll = new SupplierBLL();
        IList<Unit> _allUnits = null;
        IList<Warehouse> _warehouses = null;
        IList<LogisticsModel> _logisticsModels = null;
        IList<Supplier> _suppliers = null;
        /// <summary>
        /// 双击货品列表行时发生的事件
        /// </summary>
        public event ProductSelectedEventHandler ProductSelected = null;
        private string _proName, _proSN, _proSpec, _proBarcode;
        private int _typeId = 0;
        private bool _hasChange = false;
        private bool _inited = false;
        public ProductForm()
        {
            InitializeComponent();
        }

        private void tsbSave_Click(object sender, EventArgs e)
        {
            SaveProInfo();
        }

        /// <summary>
        /// 获取或设置双击货品列表行时的动作
        /// </summary>
        public ActionTypes DoubleListRowAction
        {
            get { return _doubleListRowAction; }
            set { _doubleListRowAction = value; }
        }

        private void tsbDelete_Click(object sender, EventArgs e)
        {
            IList<Product> datas = (IList<Product>)kdgvProduct.DataSource;
            ITransaction trans = HBHelper.BeginTransaction();
            try
            {
                foreach (DataGridViewRow r in kdgvProduct.SelectedRows)
                {
                    Product pro = r.DataBoundItem as Product;
                    if (pro != null)
                    {
                        _productBll.Delete(pro.ProductId);
                    }
                    datas.RemoveAt(r.Index);
                }
                trans.Commit();
            }
            catch (HibernateException ex)
            {
                trans.Rollback();
            }
            finally
            {
                HBHelper.Close();
            }
            kdgvProduct.Refresh();
        }

        private void tsbSearch_Click(object sender, EventArgs e)
        {
            _proBarcode = kTbxBarcode.Text.Trim();
            _proName = kTbxName.Text.Trim();
            _proSN = kTbxSN.Text.Trim();
            _proSpec = kTbxSpec.Text.Trim();
            LoadData();
        }

        private void tsbExport_Click(object sender, EventArgs e)
        {

        }

        private void ProductForm_Load(object sender, EventArgs e)
        {
            if (!this.DesignMode)
            {
                LoadData();

                FillUnit();

                FilllogisticsModel();

                FillWarehouse();

                FillSupplier();
                _inited = true;
            }
        }

        void FillSupplier()
        {
            _suppliers = _supplierBll.FindAll();
            foreach (Supplier s in _suppliers)
            {
                DCSupplier.Items.Add(s.SupplierName);
            }
        }

        void FillWarehouse()
        {
            _warehouses = _warehouseBll.FindAll();
            foreach (Warehouse w in _warehouses)
            {
                DCWarehouse.Items.Add(w.Name);
            }
        }

        void FillUnit()
        {
            _allUnits = _unitBll.FindAll();
            foreach (Unit u in _allUnits)
            {
                DCUnit.Items.Add(u.UnitName);
                DCDefUnit.Items.Add(u.UnitName);
            }
        }

        void FilllogisticsModel()
        {
            _logisticsModels = _logisticsModelBll.FindAll();

            foreach (LogisticsModel lm in _logisticsModels)
            {
                DCLogisticsModel.Items.Add(lm.LogisticsModelName);
            }
        }

        /// <summary>
        /// 载入货品数据
        /// </summary>
        public void LoadData()
        {
            if (_hasChange && _inited)
            {
                DialogResult dr = MessageBox.Show("当前信息有改动，是否保存?", "确认", MessageBoxButtons.OKCancel);
                if (dr == System.Windows.Forms.DialogResult.OK)
                {
                    SaveProInfo();
                }
            }
            PageModel<Product> pageModel = _productBll.Find(_typeId, kTbxSN.Text, kTbxName.Text, kTbxBarcode.Text, kTbxSpec.Text, pager1.PageStart, pager1.PageSize);
            pager1.TotalCount = pageModel.TotalCount;
            kdgvProduct.DataSource = new BindingList<Product>(pageModel.Results);
            _hasChange = false;
        }

        private void SaveProInfo()
        {
            ITransaction trans = HBHelper.BeginTransaction();
            try
            {
                foreach (DataGridViewRow r in kdgvProduct.Rows)
                {
                    Product product = r.DataBoundItem as Product;
                    if (product == null)
                        continue;
                    if (product.ProductId == 0)
                    {
                        _productBll.Save(product);
                    }
                    else if ("1".Equals(r.Tag) && product.ProductId != 0)
                    {
                        _productBll.Update(product);
                    }
                    r.Tag = null;
                }
                trans.Commit();
            }
            catch (HibernateException ex)
            {
                trans.Rollback();
            }
            finally
            {
                HBHelper.Close();
            }
        }

        private void kdgvProduct_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            Product p = kdgvProduct.Rows[e.RowIndex].DataBoundItem as Product;
            if (p != null)
            {
                string colName = kdgvProduct.Columns[e.ColumnIndex].Name;
                if (colName == "DCTypeName" && p.Type != null)
                {
                    e.Value = string.Format("{0}[{1}]", p.Type.TypeName, p.Type.TypeCode);
                }
                else if (colName == "DCUnit" && p.Unit != null)
                {
                    e.Value = p.Unit.UnitName;
                }
                else if (colName == "DCDefUnit" && p.DefUnit != null)
                {
                    e.Value = p.DefUnit.UnitName;
                }
                else if (colName == "DCEnabled")
                {
                    e.Value = "Y".Equals(p.Enabled) ? false : true;
                }
                else if (colName == "DCAllowOut")
                {
                    e.Value = "Y".Equals(p.AllowOut) ? true : false;
                }
                else if (colName == "DCAllowOrder")
                {
                    e.Value = "Y".Equals(p.AllowOrder) ? true : false;
                }
                else if (colName == "DCAutoReplPro")
                {
                    e.Value = "Y".Equals(p.AutoReplPro) ? true : false;
                }
                else if (colName == "DCUnitTrans")
                {
                    e.Value = "Y".Equals(p.UnitTrans) ? true : false;
                }
                else if (colName == "DCLogisticsModel" && p.LogisticsModel != null)
                {
                    e.Value = p.LogisticsModel.LogisticsModelName;
                }
                else if (colName == "DCAccType" && p.AccType >0)
                {
                    e.Value = DCAccType.Items[p.AccType - 1];
                }
                else if (colName == "DCWarehouse" && p.Warehouse != null)
                {
                    e.Value = p.Warehouse.Name;
                }
                else if (colName == "DCSupplier" && p.Supplier != null)
                {
                    e.Value = p.Supplier.SupplierName;
                }
                else if (colName == "DCProductAttr" && p.ProductAttr > 0)
                {
                    e.Value = DCProductAttr.Items[p.ProductAttr - 1];    
                }
            }
        }

        private void pager1_PageChanged(object sender, EventArgs e)
        {
            LoadData();
        }

        private void tsbSelected_Click(object sender, EventArgs e)
        {
            if (ProductSelected != null)
            {
                IList<Product> products = new List<Product>();
                foreach (DataGridViewRow r in kdgvProduct.SelectedRows)
                {
                    Product p = r.DataBoundItem as Product;
                    if (p != null)
                        products.Add(p);
                }
                ProductSelected(this, new ProductSelectedEventArgs(products));
            }
        }

        private void kdgvProduct_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                Product p = kdgvProduct.Rows[e.RowIndex].DataBoundItem as Product;
                if (DoubleListRowAction == ActionTypes.None || DoubleListRowAction == ActionTypes.DoubleToEdit)
                {
                    //ProductEditForm pef = new ProductEditForm();
                    //pef.Product = p;
                    //pef.Show();
                }
                else if (DoubleListRowAction == ActionTypes.DoubleToReturn && ProductSelected != null)
                {
                    ProductSelected(this, new ProductSelectedEventArgs(p));
                }
            }
        }

        private void productTypeControl1_ProductTypeSelected(object sender, ProductTypeSelectedEventArgs e)
        {
            if (e.SelectedProductType != null)
            {
                _typeId = e.SelectedProductType.TypeId;
                LoadData();
            }
            else if (_typeId > 0)
            {
                _typeId = 0;
                LoadData();
            }
        }

        private void kdgvProduct_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            _hasChange = true;
            if (e.RowIndex > -1)
            {
                kdgvProduct.Rows[e.RowIndex].Tag = "1";
                IList<Product> products = kdgvProduct.DataSource as IList<Product>;

                DataGridViewCell cell = kdgvProduct.Rows[e.RowIndex].Cells[e.ColumnIndex];
                string name = cell.OwningColumn.Name;
                if (name == "DCAllowOrder")
                {
                    DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)cell;
                    products[e.RowIndex].AllowOrder = ((Boolean)checkCell.Value) ? "Y" : "N";
                    kdgvProduct.Invalidate();
                }
                else if (name == "DCAllowOut")
                {
                    DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)cell;
                    products[e.RowIndex].AllowOut = ((Boolean)checkCell.Value) ? "Y" : "N";
                    kdgvProduct.Invalidate();
                }
                else if (name == "DCEnabled")
                {
                    DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)cell;
                    products[e.RowIndex].Enabled = ((Boolean)checkCell.Value) ? "N" : "Y";
                    kdgvProduct.Invalidate();

                }
                else if (name == "DCAutoReplPro")
                {
                    DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)cell;
                    products[e.RowIndex].AutoReplPro = ((Boolean)checkCell.Value) ? "Y" : "N";
                    kdgvProduct.Invalidate();
                }
                else if (name == "DCUnitTrans")
                {
                    DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)cell;
                    products[e.RowIndex].UnitTrans = ((Boolean)checkCell.Value) ? "Y" : "N";
                    kdgvProduct.Invalidate();
                }
                else if (name == "DCTypeName")
                {
                    string code = cell.Value.ToString();
                    ProductType proType = _productTypeBll.GetByCode(code);
                    if (proType == null)
                    {
                        kdgvProduct.CancelEdit();
                    }
                    else
                    {
                        products[e.RowIndex].Type = proType;
                    }
                }

            }
        }

        private void kdgvProduct_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.Cancel = false;
        }

        private void kdgvProduct_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void kdgvProduct_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            string colName = kdgvProduct.Columns[kdgvProduct.CurrentCell.ColumnIndex].Name;
            IList<Product> datas = (IList<Product>)kdgvProduct.DataSource;
            KryptonDataGridViewComboBoxEditingControl cbc = e.Control as KryptonDataGridViewComboBoxEditingControl;
            if (cbc != null)
            {
                cbc.DropDownClosed += new EventHandler(cbc_DropDownClosed);
            }

        }

        void cbc_DropDownClosed(object sender, EventArgs e)
        {
            IList<Product> datas = (IList<Product>)kdgvProduct.DataSource;
            KryptonDataGridViewComboBoxEditingControl cbc = sender as KryptonDataGridViewComboBoxEditingControl;
            string colName = kdgvProduct.Columns[kdgvProduct.CurrentCell.ColumnIndex].Name;

            if (colName == "DCUnit" && cbc.SelectedIndex > -1)
            {
                datas[kdgvProduct.CurrentCell.RowIndex].Unit = _allUnits[cbc.SelectedIndex];
            }
            else if (colName == "DCDefUnit" && cbc.SelectedIndex > -1)
            {
                datas[kdgvProduct.CurrentCell.RowIndex].DefUnit = _allUnits[cbc.SelectedIndex];
            }
            else if (colName == "DCWarehouse" && cbc.SelectedIndex > -1)
            {
                datas[kdgvProduct.CurrentCell.RowIndex].Warehouse = _warehouses[cbc.SelectedIndex];
            }
            else if (colName == "DCAccType" && cbc.SelectedIndex > -1)
            {
                datas[kdgvProduct.CurrentCell.RowIndex].AccType = (short)(cbc.SelectedIndex + 1);
            }
            else if (colName == "DCSupplier" && cbc.SelectedIndex > -1)
            {
                datas[kdgvProduct.CurrentCell.RowIndex].Supplier = _suppliers[cbc.SelectedIndex];
            }
            else if (colName == "DCProductAttr" && cbc.SelectedIndex > -1)
            {
                datas[kdgvProduct.CurrentCell.RowIndex].ProductAttr = cbc.SelectedIndex + 1;
            }
            else if (colName == "DCLogisticsModel" && cbc.SelectedIndex > -1)
            {
                datas[kdgvProduct.CurrentCell.RowIndex].LogisticsModel = _logisticsModels[cbc.SelectedIndex];
            }
        }
    }
}